package com.da.javatest.interview.session2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chenlida
 * @date 2020/3/31 21:58
 * @description A, B, C, 交替打印
 */
public class Test18Condition {
    private Lock lock = new ReentrantLock();
    private int num = 1;
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void print(int flag, int times, String data, Condition awaitCondition, Condition signalCondition) {
        try {
            lock.lock();
            // 用while防止虚假唤醒
            while (num != flag) {
                awaitCondition.await();
            }
            for (int i = 0; i < times; i++) {
                System.out.print(Thread.currentThread().getName() + " data:" + data + "\t");
            }
            num = flag % 3 + 1;
            signalCondition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Test18Condition t = new Test18Condition();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                t.print(1, 1, "A", t.c1, t.c2);
                System.out.println();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                t.print(2, 2, "B", t.c2, t.c3);
                System.out.println();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                t.print(3, 3, "C", t.c3, t.c1);
                System.out.println();
            }
        }, "C").start();
    }
}
